import * as THREE from 'three'

const Creater = {
  video_material (src, config = {}) {
    const sourceDom = document.createElement('source')
    sourceDom.src = src

    const videoDom = document.createElement('video')
    videoDom.setAttribute('crossorigin', 'anonymous')
    videoDom.appendChild(sourceDom)
    videoDom.loop = true
    videoDom.playsInline = true

    const material = new THREE.MeshBasicMaterial({
      ...{
        map: new THREE.VideoTexture(videoDom)
      },
      ...config
    })
    return material
  },
  image_material (src, config = {}) {
    const material = new THREE.MeshBasicMaterial({
      ...{
        map: new THREE.TextureLoader().load(src)
      },
      ...config
    })
    return material
  },
  text3D (
    text,
    callback,
    config = {
      size: 0.12,
      height: 0.01,
      curveSegments: 12,
      bevelThickness: 0.01,
      bevelSize: 0.001
    }
  ) {
    const loader = new THREE.FontLoader()
    let txtMesh = null
    loader.load('fonts/STXingkai_Regular.json', (font) => {
      const txtGeo = new THREE.TextGeometry(text, { ...{ font }, ...config })
      txtGeo.center()
      const txtMater = new THREE.MeshBasicMaterial({ color: '#ffffff' })
      txtMesh = new THREE.Mesh(txtGeo, txtMater)
      callback(txtMesh)
    })
  },
  text2D (message, height = 0.18) {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    let metrics = null
    const textHeight = 100
    context.font = 'normal ' + textHeight + 'px Arial'
    metrics = context.measureText(message)
    const textWidth = metrics.width
    canvas.width = textWidth
    canvas.height = textHeight
    context.font = 'normal ' + textHeight + 'px Arial'
    context.textAlign = 'center'
    context.textBaseline = 'middle'
    context.fillStyle = '#ffffff'
    context.fillText(message, textWidth / 2, textHeight / 2)

    const texture = new THREE.Texture(canvas)
    texture.needsUpdate = true
    const material = new THREE.MeshBasicMaterial({
      map: texture,
      transparent: true
    })
    const geometry = new THREE.PlaneGeometry(
      (height * textWidth) / textHeight,
      height
    )
    const plane = new THREE.Mesh(geometry, material)
    return plane
  }
}

export default Creater
